'use strict';

const { isObject } = require("@duo-cli/utils");
const pkgdir = require('pkg-dir').sync;
const path = require('path');
const formatPath = require('@duo-cli/format-path');
const npminstall = require('npminstall');
const fse = require("fs-extra");
const { getDefaultRegistry, getNpmLatestVersion } = require('@duo-cli/get-npm-info');
const pathExists = require('path-exists').sync;

class Package {
  constructor(options) {
    if (!options) {
      throw new Error('Package类的options参数不能为空！');
    }
    if (!isObject(options)) {
      throw new Error('Package类的targetPath参数必须为对象！');
    }

    // package的路径
    this.targetPath = options.targetPath;
    // package的name
    this.packageName = options.packageName;
    // package的version
    this.packageVersion = options.packageVersion;
    // package的缓存路径
    this.storeDir = options.storeDir;
    // package的缓存目录前缀
    this.cahcheFilePathPrefix = this.packageName.replace('/', '+');
  }

  async prepare() {
    if (this.storeDir && !pathExists(this.storeDir)) {
      fse.mkdirpSync(this.storeDir);
    }
    if (this.packageVersion === 'latest') {
      this.packageVersion = await getNpmLatestVersion(this.packageName);
    } 
  }

  get cacheFilePath() {
    return path.resolve(
      this.storeDir,
      `.store\\${this.cahcheFilePathPrefix}@${this.packageVersion}\\node_modules\\${this.packageName}`
    )
  }

  getSpecificCacheFilePath(packageVersion) {
    return path.resolve(
      this.storeDir,
      `.store\\${this.cahcheFilePathPrefix}@${packageVersion}\\node_modules\\${this.packageName}`
    )
  }

  // 判断当前package是否存在
  async exists() {
    if (this.storeDir) {
      await this.prepare();
      console.log('this.cacheFilePath>', this.cacheFilePath);
      return pathExists(this.cacheFilePath);
    } else {
      return pathExists(this.targetPath);
    }
  }

  // 安装package
  async install() {
    await this.prepare();
    return npminstall({
      root: this.targetPath,
      storeDir: this.storeDir,
      registry: getDefaultRegistry(),
      pkgs: [
        { name: this.packageName, version: this.packageVersion }
      ]
    });
  }

  // 更新package
  async update() {
    await this.prepare();
    // 获取最新版本号
    const latestPackageVersion = await getNpmLatestVersion(this.packageName);
    console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", latestPackageVersion);
    const latestFilePath = this.getSpecificCacheFilePath(latestPackageVersion);
    if (!pathExists(latestFilePath)) {
      await npminstall({
        root: this.targetPath,
        storeDir: this.storeDir,
        registry: getDefaultRegistry(),
        pkgs: [ 
          { name: this.packageName, version: latestPackageVersion }
        ]
      });
      this.packageVersion = latestPackageVersion;
    }
  }

  // 获取package的入口文件路径
  getRootFilePath() {
    function _getRootFile(targetPath) {
      const dir = pkgdir(targetPath);
      if (dir) {
        //读取package.json -- require() js/json/node
        const pkgFile = require(path.resolve(dir, 'package.json'))
        //寻找main/lib -> path
        if (pkgFile && (pkgFile.main)) {
          //路径兼容（mocOS/windows）
          return formatPath(path.resolve(dir, pkgFile.main))
        }
      }
      return null
    }
    //获取package.json所在目录 -- pkg-dir
    if (this.storeDir) {
      //使用缓存
      return _getRootFile(this.cacheFilePath)
    } else {
      return _getRootFile(this.targetPath)
    }
  }
}

module.exports = Package;
